package com.MTR;


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Map.Entry;

import javax.swing.*;


public class TrainPanel extends JScrollPane implements ComponentListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2800319481625166815L;

	// train labels
	protected TreeMap<Integer, TrainDispLabel> arr = new TreeMap<Integer, TrainDispLabel>();
	
	protected JPanel panel = null;
	
	public TrainPanel() {
		super();
		
		panel = new JPanel();
		panel.setLayout(new FlowLayout());
		
		// load train from database
		TreeMap<Integer, String> trains = DerbyWrapper.instance().loadTrains();
		
		Iterator<Entry<Integer, String>> it = trains.entrySet().iterator();
		while (it.hasNext())
		{
			Map.Entry<Integer, String> entry = it.next();
			int idx = entry.getKey();
			String val = entry.getValue();
			TrainDispLabel l = new TrainDispLabel(idx, val);
			
			// add to list
			TrainPanel.this.arr.put(idx, l);
			// add to ui
			panel.add(l);
		}
		
		// add the inner panel
		this.add(panel);
		
		this.setViewportView(panel);
		
		// register data receive event
		DataReceiver.instance().addDataReceiveListener(new DataReceiveListener() {
			
			@Override
			public void dataReceived(DataReceiveEvent e) {
				// Set UI
				MoteData d = e.getData();
				// FIXME: shall we set according to vehicle ID?
				TrainDispLabel l = TrainPanel.this.arr.get(d.nodeID);
				if (l != null)
				{
					l.setDisplay(d, 0);
				}
				
			}
		});
		
		this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		
		// add listener
		this.addComponentListener(this);
		
		// FIXME remove testing data
		MoteData d = new MoteData();
		
		TrainDispLabel tp = this.arr.get(1);
		tp.setDisplay(d, 0);
		
		d = new MoteData();
		d.vehicleID = 0;
		d.nodeID = 0;
		d.temperature = 55.5;
		tp = this.arr.get(3);
		tp.setDisplay(d, 0);
		
		d = new MoteData();
		d.vehicleID = 2;
		d.nodeID = 0;
		d.temperature = 65.5;
		tp = this.arr.get(5);
		tp.setDisplay(d, 0);
		
	}

	@Override
	public void componentHidden(ComponentEvent e) {
		
	}

	@Override
	public void componentMoved(ComponentEvent e) {
		
	}

	@Override
	public void componentResized(ComponentEvent e) {
		// calculate the preferred size of JPanel
		Dimension dSingle = arr.firstEntry().getValue().getPreferredSize();
		
		// total square
		int total = this.arr.size() * (dSingle.height + 15) * (dSingle.width + 15);
		int myWidth = this.getWidth() - this.getVerticalScrollBar().getWidth() - 5;
		int pWidth = myWidth > 640 ? myWidth : 640;	// this is preferred with, minimum is 640.
		int pHeight = total / pWidth;
		this.panel.setPreferredSize(new Dimension(pWidth, pHeight));
		
	}

	@Override
	public void componentShown(ComponentEvent e) {
		
	}

}
